package com.example.jooqdemo.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description: java类作用描述
 * @Author: czw
 * @date: 2018/4/28
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    private static final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class);

    @Autowired
    private LogInterceptor logInterceptor;

    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor);
        registry.addInterceptor(new SessionInterceptors()).addPathPatterns("/**");
    }
    class SessionInterceptors implements HandlerInterceptor{
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
            showParams(request);
            Object user = request.getSession().getAttribute("user");
            if(user == null ){
                return false;
            }else{
                return true;
            }
        }

        /**
         * 获取请求参数
         * @param request
         */
        private void showParams(HttpServletRequest request) {
            Map map = new HashMap();
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        map.put(paramName, paramValue);
                    }
                }
            }
            System.out.println("------------------------------");
            for(Object key : map.keySet()){
                System.out.println(map.get(key));
            }
            System.out.println("------------------------------");
        }
    }
}
